package com.jelly.concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 优先级
 * @author Jelly
 *
 */
public class SimplePriorities implements Runnable{

	private int countDwon=5;
	private volatile double d; //No optimization
	private int priority;
	
	public SimplePriorities(int proority){
		this.priority=proority;
	}
	
	@Override
	public String toString() {
		return Thread.currentThread()+":  "+countDwon;
	}
	
	@Override
	public void run() {
		Thread.currentThread().setPriority(priority);
		while(true){
			//An expensive interruptable operation
			for (int i = 0; i < 100000; i++) {
				d+=(Math.PI+Math.E)/(double)i;
				if(i%1000==0){
					Thread.yield();
				}
				System.out.println(this);
				if(--countDwon==0){
					return;
				}
			}
		}
	}
	
	public static void main(String[] args) {
		ExecutorService exec = Executors.newCachedThreadPool();
		for (int i = 0; i < 5; i++) {
			exec.execute(new SimplePriorities(Thread.MIN_PRIORITY));
		}
		exec.execute(new SimplePriorities(Thread.MAX_PRIORITY));
		exec.shutdown();
	}

}
